﻿#include "videoitem.h"
#include <QSGTexture>
#include <QQuickWindow>

VideoItem::VideoItem(QQuickItem *parent) : QQuickItem(parent) {
    setFlag(ItemHasContents, true);
    setAcceptedMouseButtons(Qt::AllButtons);
}

VideoItem::~VideoItem() {
    if (m_lastTexture) {
        delete m_lastTexture;
        m_lastTexture = nullptr;
    }
}

QImage VideoItem::frame() const {
    QMutexLocker locker(&m_frameMutex);
    return m_currentFrame ? *m_currentFrame : QImage();
}

void VideoItem::setFrame(const QImage &frame) {
    QSharedPointer<QImage> newFrame(new QImage(frame));

    {
        QMutexLocker locker(&m_frameMutex);
        m_currentFrame.swap(newFrame);
    }

    update();
    emit frameChanged();
}

QSGNode *VideoItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) {
    QSGSimpleTextureNode *node = static_cast<QSGSimpleTextureNode *>(oldNode);

    QMutexLocker locker(&m_frameMutex);
    if (!m_currentFrame || m_currentFrame->isNull()) {
        if (node) {
            delete node->texture();
            delete node;
            node = nullptr;
        }

        if (m_lastTexture) {
            delete m_lastTexture;
            m_lastTexture = nullptr;
        }

        return nullptr;
    }

    if (!node) {
        node = new QSGSimpleTextureNode();
    }

    // 删除旧纹理
    if (m_lastTexture) {
        delete m_lastTexture;
        m_lastTexture = nullptr;
    }

    // 创建新纹理
    m_lastTexture = window()->createTextureFromImage(*m_currentFrame);
    node->setTexture(m_lastTexture);
    node->setFiltering(QSGTexture::Linear);
    node->setRect(boundingRect());
    node->setSourceRect(QRectF(0, 0, m_currentFrame->width(), m_currentFrame->height()));

    // 通知前一帧已处理完成
    emit frameProcessed();

    return node;
}
